package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.RiskDimension
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR'])
@Transactional
class AccountsReceivableController
{

    def springSecurityService
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def city = params["city"]
        def estateStatus = params["estateStatus"]
        def name = params["name"]
        def risk = params["risk"]
        def mortgageStatus = params["mortgageStatus"]
        def type = params["type"]
        def cashability = params["cashability"]
        

        def user = User.findById(springSecurityService.principal.id)

        def estateQueryParam = new HashMap()
        def estateSql = " from Collateral e where e.status = 'Completed' and e.type.code = 'accountsReceivable' and e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (estateStatus && estateStatus != "")
        {
            sql += " and e.estateStatus.id = :estateStatus"
            estateQueryParam['estateStatus'] = Long.parseLong(estateStatus)
        }
        if (name && name != "")
        {
            sql += " and e.name like :name "
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (risk && risk != "")
        {
            def riskList = RiskDimension.list()
            riskList.each {
                if (it?.label == risk)
                {
                    def minValue = it.minValue / 100
                    def maxValue = it.maxValue / 100
                    sql += " and e.cltv > :minValue and e.cltv <= :maxValue "
                    estateQueryParam['minValue'] = minValue
                    estateQueryParam['maxValue'] = maxValue
                }
            }
        }
        if (type && type != "")
        {
            sql += " and e.accountsReceivable.type.id = :type "
            estateQueryParam['type'] = Long.parseLong(type)
        }
        if (cashability && cashability != "")
        {
            sql += " and e.cashability.id = :cashability "
            estateQueryParam['cashability'] = Long.parseLong(cashability)
        }

        def countSql = " select count(e.id) from Collateral e where e.status = 'Completed' and e.type.code = 'accountsReceivable' and e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql
        sql += " order by e.modifiedDate desc "
        estateSql += sql
        
        def collateralList = Collateral.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def collateralCount = Collateral.executeQuery(countSql, estateQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond collateralList, model: [collateralList: collateralList, collateralCount: collateralCount[0], districtList: districtList, params: params], view: 'index'
    }

    def show(Collateral collateral)
    {
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage
        respond collateral, model: [params: params, mortgageList: mortgageList, accountsReceivable: collateral?.accountsReceivable]
    }

    def create()
    {
        respond new AccountsReceivable(params)
    }

    def createAccountsReceivable()
    {
        def typeName = params['type']
        if (typeName == "交易类应收账款")
        {
            respond new AccountsReceivable(params), view: 'createTransaction'
            return
        }
        if (typeName == "道路收费权")
        {
            respond new AccountsReceivable(params), view: 'createRoadTollRight'
            return
        }
        if (typeName == "出口退税专用账户")
        {
            respond new AccountsReceivable(params), view: 'createExportTaxRebate'
            return
        }
        if (typeName == "其他类应收账款")
        {
            respond new AccountsReceivable(params), view: 'createOthers'
            return
        }
    }

    @Transactional
    def save(AccountsReceivable accountsReceivable)
    {
        if (accountsReceivable == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (accountsReceivable.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond accountsReceivable.errors, view: 'create'
            return
        }
        if (accountsReceivable.validate())
        {
            accountsReceivable.save flush: true
        }
        else
        {
            println accountsReceivable.errors
        }
        def collateral = new Collateral()
        collateral.province = accountsReceivable.province
        collateral.city = accountsReceivable.city
        collateral.district = accountsReceivable.district
        collateral.estateStatus = accountsReceivable.estateStatus
        collateral.isEstate = accountsReceivable.isEstate
        collateral.unitPrice = accountsReceivable.unitPrice
        collateral.totalPrice = accountsReceivable.totalPrice
        collateral.valuationDate = accountsReceivable.valuationDate
        collateral.ltv = accountsReceivable.ltv
        collateral.cltv = accountsReceivable.cltv
        collateral.account = accountsReceivable.account
        collateral.externalId = accountsReceivable.externalId
        collateral.name = accountsReceivable.name
        collateral.fullName = accountsReceivable.fullName
        collateral.identityType = accountsReceivable.identityType
        collateral.idNumber = accountsReceivable.idNumber
        collateral.loanCardNumber = accountsReceivable.loanCardNumber
        collateral.commonOwnerFullName = accountsReceivable.commonOwnerFullName
        collateral.sharePoint = accountsReceivable.sharePoint
        collateral.cashability = accountsReceivable.cashability
        collateral.valueVolatility = accountsReceivable.valueVolatility
        collateral.seizureOfConvenience = accountsReceivable.seizureOfConvenience
        collateral.relationOfMortgagor = accountsReceivable.relationOfMortgagor
        collateral.legalValidity = accountsReceivable.legalValidity
        collateral.firstEvaluatePrice = accountsReceivable.firstEvaluatePrice
        collateral.latestEvaluatePrice = accountsReceivable.latestEvaluatePrice
        collateral.latestEvaluateDate = accountsReceivable.latestEvaluateDate
        collateral.actualMortgageRate = accountsReceivable.actualMortgageRate
        collateral.mortgageRateUpperLimit = accountsReceivable.mortgageRateUpperLimit
        collateral.description = accountsReceivable.description
        collateral.registerFullName = accountsReceivable.registerFullName
        collateral.registerAccount = accountsReceivable.registerAccount
        collateral.registerDate = accountsReceivable.registerDate
        collateral.registerUpdateDate = accountsReceivable.registerUpdateDate
        collateral.accountsReceivable = accountsReceivable
        collateral.sourceClass = "accountsReceivable"
        collateral.type = CollateralType.findByCode("accountsReceivable")
        collateral.status = "Completed"
        collateral.stage = CollateralStage.findByCode("21")
        if (collateral.validate())
        {
            collateral.save flush: true
        }
        else
        {
            println collateral.errors
        }

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        mortgageList.each
        {
            def mortgageCollateral = new MortgageCollateral()
            mortgageCollateral.collateral = collateral
            mortgageCollateral.mortgage = Mortgage.findById(it)
            if (mortgageCollateral.validate()) 
            {
                mortgageCollateral.save flush: true
            }
            else
            {
                println mortgageCollateral.errors
            }

            // def mortgageContact = new MortgageContact()
            // mortgageContact.mortgage = Mortgage.findById(it)
            // mortgageContact.contact = Mortgage.findById(it)?.mortgageContact
            // mortgageContact.type = ContactType.findByCode("1")
            // if (mortgageContact.validate()) 
            // {
            //     mortgageContact.save flush: true    
            // }
            // else
            // {
            //     println mortgageContact.errors
            // }
        }
        
        redirect action: 'show', params: [id: collateral?.id]
    }

    def edit(AccountsReceivable accountsReceivable)
    {
        respond accountsReceivable
    }

    @Transactional
    def update(AccountsReceivable accountsReceivable)
    {
        if (accountsReceivable == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (accountsReceivable.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond accountsReceivable.errors, view: 'edit'
            return
        }

        accountsReceivable.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'accountsReceivable.label', default: 'AccountsReceivable'), accountsReceivable.id])
                redirect accountsReceivable
            }
            '*' { respond accountsReceivable, [status: OK] }
        }
    }

    @Transactional
    def delete(AccountsReceivable accountsReceivable)
    {

        if (accountsReceivable == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        accountsReceivable.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'accountsReceivable.label', default: 'AccountsReceivable'), accountsReceivable.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'accountsReceivable.label', default: 'AccountsReceivable'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
